<template>
  <div v-if="!isShow">
    <el-card>
      <div class="card-wrap">
        <el-page-header content="添加后评价信息" @back="handleBack" />
        <div
          v-if="
            projectInfo?.saveStatus !== '7' &&
            projectInfo?.stageStatus === '5' &&
            route.query.mode !== 'look'
          "
        >
          <el-button @click="goBack">取消</el-button>
          <template v-if="!isApproval">
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="handleSave"
              >保存</el-button
            >
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="handleSubmit"
              >提交</el-button
            >
          </template>
          <template v-if="isApproval">
            <el-button type="primary" @click="reject">驳回</el-button>
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="approve"
              >通过</el-button
            >
          </template>
        </div>
      </div>
    </el-card>
    <br />

    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>项目基本信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show1">
        <BasicsInfo :projectInfo="projectInfo" />
      </div>
    </el-card>
    <br />

    <template v-if="route.query.instanceId">
      <el-card class="expert-card">
        <template #header>
          <div class="card-box-header">
            <span>专家评审意见</span>
            <div v-if="show3" @click="show3 = !show3" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show3 = !show3" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show3">
          <ExperReviewtList :projectInfo="projectInfo" />
          <BuildApproval
            :projectInfo="projectInfo"
            class="mg-top"
          ></BuildApproval>
        </div>
      </el-card>
      <br />
    </template>

    <el-card v-if="route.query.instanceId">
      <template #header>
        <div class="card-box-header">
          <span> 流程状态</span>
        </div>
      </template>
      <div>
        <el-collapse-transition v-if="currentStep">
          <!-- <status-info
            :currentStep="currentStep"
            :steps="steps"
            :isSkip="isSkipAlter"
          /> -->
          <img :src="currentStep" />
        </el-collapse-transition>
      </div>
    </el-card>
    <br />
    <el-card v-if="route.query.instanceId">
      <template #header>
        <div class="card-box-header">
          <span> 流转记录</span>
        </div>
      </template>
      <div>
        <el-collapse-transition>
          <approval-info :activities="approveRecord" />
        </el-collapse-transition>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import BasicsInfo from "../../detail/components/BasicsInfo.vue";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import ExperReviewtList from "/@/views/approval/detail/components/ExperReviewtList.vue";
import BuildApproval from "/@/views/approval/detail/components/BuildApproval.vue";

import {
  getProjectInfo,
  updateEvaluation,
  getEvaluationById,
  submitStage,
  rejectStage,
  approveStage
} from "/@/api/project";
import { getApproveHistory } from "/@/api/project";
import { cloneDeep } from "lodash-es";
import { flowTypeCode } from "../../create/types";
import NotifMessage from "/@/utils/message/notification";
import { ElMessageBox } from "element-plus";
import {getApproveImg} from "/@/api/project";
const router = useRouter();
const route = useRoute();
const currentStep = ref(null);
const steps = ref([]);
const approveRecord = ref([]);
const authorSelectTable = ref(null);
const formRef = ref<HTMLFormElement | null>(null) as any;
let model = reactive({
  saveLoading: false,
  defaultFileList: [],
  dones: [
    { key: true, label: "是" },
    { key: false, label: "否" }
  ],
  formData: {
    memberList: [],
    evaluationTime: "",
    remark: "",
    evaluationMembers: [],
    evaluationResult: "",
    evaluationReport: []
  },
  flowType: ""
});

let show1 = ref<boolean>(true);
let show3 = ref<boolean>(true);

const handleBack = () => {
  router.replace("/project/evaluate");
};

let projectInfo = ref(null);

const goBack = (): void => {
  router.push("/project/evaluate");
};

const handleSubmit = async () => {
  model.saveLoading = true;
  const flag = await handleSave(false);
  model.saveLoading = false;

  if (!flag) {
    model.saveLoading = true;
    const { code, message } = await submitStage(route.query.id);
    model.saveLoading = false;
    if (code === 200) {
      NotifMessage.success(message);
      goBack();
    }
  }
};
const handleSave = async (flag = true): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  try {
    if (isValid) {
      const copyFormData = cloneDeep(model.formData);
      copyFormData.projectId = +route.query.id;

      copyFormData.evaluationMembers = JSON.stringify(
        authorSelectTable.value.participantList
      );
      copyFormData.evaluationReport = JSON.stringify(
        copyFormData.evaluationReport
      );
      model.saveLoading = true;
      const { code, message } = await updateEvaluation(copyFormData);
      model.saveLoading = false;
      if (code === 200) {
        if (flag) {
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      } else {
        NotifMessage.error(message);
      }
    } else {
      NotifMessage.warning("请补充必填信息后，再次操作！");
      return true;
    }
  } catch (err) {
    return true;
  }
};

// 删除记录
const initProjectInfo = async () => {
  try {
    const queryId = route.query?.id ?? "";
    const { code, data } = queryId && (await getProjectInfo({ id: queryId }));
    if (code === 200) {
      projectInfo.value = data;
      projectInfo.value.projectManageId = +route.query.id;
      projectInfo.value.reviewStageCode = 5;
      const emyp = data.approveTypeMaxCode + "," + data.approveTypeMinCode;
      model.flowType = flowTypeCode[emyp];
    }
    const res = await getEvaluationById(queryId);
    if (res.code === 200 && res.data != null) {
      if (res.data.evaluateResult === "2") {
        model.flowType = "2028";
      }
      if (model.flowType) {
        getStep();
      }
      // model.formData = res.data;

      // model.formData.evaluationMembers == null
      //   ? []
      //   : (model.formData.evaluationMembers = JSON.parse(
      //       res.data.evaluationMembers
      //     ));

      // if (model.formData.evaluationReport) {
      //   model.formData.evaluationReport = JSON.parse(res.data.evaluationReport);
      //   model.defaultFileList = model.formData.evaluationReport;
      //   model.defaultFileList.forEach(el => {
      //     el["name"] = el.fileName;
      //   });
      // }
      // console.log(res.data, "data");
    }
  } catch (err) {
    console.log(err);
  }
};
const reject = async () => {
  ElMessageBox.prompt("请输入驳回原因:", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // inputPlaceholder: "请填写变更申请原因",
    inputType: "textarea",
    inputValidator(value) {
      if (value == undefined) {
        return "内容不能为空";
      } else if (value.length == 0) {
        return "内容不能为空";
      } else if (value.length > 300) {
        return "请输入300个字符以内的内容";
      }
    },

    inputErrorMessage: "请输入驳回原因"
  })
    .then(async ({ value }) => {
      const { code, message } = await rejectStage({
        id: route.query.id,
        reason: value
      });
      if (code === 200) {
        NotifMessage.success("驳回成功");
        goBack();
      } else {
        NotifMessage.error(message);
      }
    })
    .catch(err => {
      console.log(err);
    });
};

//查询流程审批记录
const getApproveHistoryList = async instanceId => {
  const { code, data } = await getApproveHistory(instanceId);
  if (code === 200) {
    approveRecord.value = data;
  }
};

//获取流程转态
const getStep = async () => {
  const instanceId = route.query.instanceId;
    const { code, data } = await getApproveImg(instanceId);
    if (code === 200) {
      currentStep.value = data;
    }
};

const approve = async () => {
  model.saveLoading = true;
  const { code, message } = await approveStage(route.query.id);
  model.saveLoading = false;
  if (code === 200) {
    NotifMessage.success("审核成功");
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

onMounted(() => {
  if (route.query.id) {
    initProjectInfo();
  }
  if (route.query.instanceId) {
    getApproveHistoryList(route.query.instanceId);
  }
});

const isApproval =
  route.query.mode === "approval" || route.query.mode === "look" ? true : false;
</script>

<style lang="scss" scoped>
.empt-content {
  height: calc(100vh - 200px);
  width: 100%;
}
.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}
.mg-top {
  margin-top: 20px;
}
</style>
